<template>
  <div
    class="my-chart"
    ref="myChartRef"
  />
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, watch, onMounted, onUnmounted, nextTick, PropType } from 'vue';
import * as echarts from 'echarts';
import { EChartsType, EChartsOption } from 'echarts'
import { isObjectEmpty } from 'src/util/utils';

export default defineComponent({
  name: 'ViewChart',
  props: {
    options: {
      type: Object,
      default: {} as EChartsOption
    }
  },
  setup (props, context) {
    // 不是响应对象，否则会出错
    let myChartInstance: EChartsType;

    //响应数据
    let myChartRef = ref<HTMLElement | null>(null); // dom
    const {
      options
    } = toRefs(props);

    // 设置选择项
    const setChartOption = () => {
      if (!isObjectEmpty(myChartInstance)) {
        // 写入绘图
        myChartInstance.setOption(options.value, true);
      }
    };

    // 尺寸变化
    const onResize = () => {
      if (myChartInstance) {
        myChartInstance.resize();
      }
    };

    // 更新视图
    const updateView = () => {
      setChartOption();
    };

    // 监视option变化
    watch(() => options, () => {
      setChartOption();
    }, { deep: true });

    // 挂载组件
    onMounted(() => {
      nextTick(() => {
        if (myChartRef.value !== null) {
          myChartInstance = echarts.init(myChartRef.value);
          setChartOption();
        }
      });

      // 跟随窗口变化
      window.addEventListener('resize', onResize);
    });

    // 卸载组件
    onUnmounted(() => {
      window.removeEventListener('resize', onResize);
    });

    return {
      myChartRef,
      options,
      onResize,
      updateView
    };
  }
});
</script>

<style lang="scss" scoped>
.my-chart {
  height: 100%;
  width: 100%;

  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
